import {
  getPage,
  getImage
} from '../../utils/config';
import {
  imageCdn
} from '../../utils/api';
import {
  prosimify,
  $toast,
  http,
  storage,
  SubscribeMessage
} from '../../utils/utils';
import uploadImage from '../../utils/aliyunoss/uploadAliyun';
import wxApi from '../../utils/wxApi';
import api from '../../utils/api';
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    getPage: getPage,
    getImage: getImage,
    initial: 0,
    userId: 0,
    userRank: 0,
    logged: 0,
    userInfo: {},
    userData: {},
    show: false,
    rankbg: "",
    rankname: "",
    nickname: "微信用户",
    myTime: null,
    wxinfo: {
      avatar: '',
      nickname: ''
    },
    iswxbind: false,
    bindwx: false,
    dialogConfirm: false,
    hfListIndex: 0,
    botZtListIndex: 0,
    botZtList:[]
  },

  handleScan(){
    wx.scanCode({
      success: function(res) {
          console.log('扫码获取的参数',res)
          let str = res.result;
          console.log(str);
          if (str.indexOf('https') === 0 || str.indexOf('http') === 0){
            if(str.indexOf('https://shop.keju123.com/hexiao') === 0){
                var id = str.split('hexiao/')[1];
                console.log('iiiiiiii',id)
                wxApi.navigateTo(getPage.hexiao,{id});
            }
            else{
              wxApi.navigateTo("/pages/web/web?id=" + str);
            }
          }else{
            $toast(str,{
              icon:'fail',
              times:3000
            })
          }
      }
    })
  },

  botZtListChange(e) {
    this.setData({
      botZtListIndex: e.detail.current
    })
  },

  showPopup() {
    console.log(123);
    this.setData({
      show: true
    });
  },

  onClose() {
    this.setData({
      show: false
    });
  },
  /**
   * 跳转登录
   */
  goLogin() {
    wxApi.setStartPage();
    wxApi.navigateTo(getPage.login);
  },
  goCoupon() {
    wxApi.navigateTo(getPage.couponList);
  },
  goChoujiang() {
    wxApi.navigateTo(getPage.choujiang);
  },
  gozhuangxiu() {
    wxApi.navigateTo(getPage.mfsheji);
  },
  clearJb(e){
    let { name } = e.currentTarget.dataset;
    console.log('eeeeeeeee',name)
    let { shopJbData,key } = this.data;
    if(name && shopJbData[name] == 1){
      shopJbData[name] = 0;
      this.setData({
        shopJbData
      })
      wx.setStorageSync(key,shopJbData)
    }
  },
  getLocation: function (e) {
    let { name } = e.currentTarget.dataset;
    let { shopJbData,key } = this.data;
    if(name && shopJbData[name] == 1){
      shopJbData[name] = 0;
      this.setData({
        shopJbData
      })
      wx.setStorageSync(key,shopJbData)
    }
    var _this = this;
    SubscribeMessage().then(()=>{
      
      wx.chooseLocation({
        success: function (res) {
          var name = res.name
          var address = res.address
          var latitude = res.latitude
          var longitude = res.longitude
          if (address != "") {
            //第二部分数据
            http.post(api.default, {
              data: {
                action: 'setshopweizhi',
                userid: _this.data.userId,
                name: name,
                address: address,
                latitude: latitude,
                longitude: longitude
              }
            }, false).then(res => {
              console.log(res)
              $toast("设置位置成功");
            });
          }
          _this.setData({
            name: name,
            address: address,
            latitude: latitude,
            longitude: longitude
          })
        },
        complete(r) {
          console.log(r)
        }
      })
    })
  },
  govip() {
    wxApi.navigateTo(getPage.vip);
    //wxApi.navigateTo(getPage.paymentFeedback);
  },

  handleNavigate(e){
    let { name } = e.currentTarget.dataset;
    let { nullShopJbData,key } = this.data;
    console.log('name',name)
    if(nullShopJbData[name] == 1){
      nullShopJbData[name] = 0;
      this.setData({
        nullShopJbData
      })
      wx.setStorageSync(key,nullShopJbData)
    }
  },

  shopGoFun(e){
    console.log('eeeeeeeeeeeee',e)
    let { goname,id,name } = e.currentTarget.dataset;
    let { shopJbData,key } = this.data;
    SubscribeMessage().then(res=>{
      console.log('resssssssss',res)
      if(name && shopJbData[name] == 1){
        shopJbData[name] = 0;
        this.setData({
          shopJbData
        })
        wx.setStorageSync(key,shopJbData)
      }
      if(id){
        wxApi.navigateTo(goname,{ id });
      }else{
        wxApi.navigateTo(goname);
      }
    })
  },

  /**
   * 跳转个人中心
   */
  goProfile() {
    this.setData({
      "wxinfo.avatar": this.imageAvatar(this.data.userInfo.user_model.head_url) || null,
      "wxinfo.nickname": this.data.nickname || '',
      iswxbind: true
    })
    // wxApi.navigateTo(getPage.userProfile);
  },
  scantest() {
    wx.scanCode({
      onlyFromCamera: false,
      success: res => {
        const path = res.path;
        const scanType = res.scanType;
        console.log(res);
        console.log("path: ", path);
      }
    });

  },
  /**
   * 底部导航点击
   */
  onTabItemTap() {
    const {
      logged,
      initial
    } = this.data;
    if (!logged && initial) {
      //判断是否登录，记录登录态
      app.getLogin().then((res) => {
        this.setData({
          localInfo: res,
          logged: res.code,
          userId: res.data.user.user_id,
          userRank: res.data.user.user_rank,
        });
        //获取页面数据
        this.getUserInfo(() => {
          let {
            localInfo,
            userInfo,
            userData
          } = this.data;
          //更新本地
          localInfo.data.user = userInfo.user_model;
          localInfo.data.shop = userData.shop;
          this.setData({
            localInfo
          });
          storage.set('userInfo', localInfo);
        });
      }).catch((res) => {
        //记录当前路径
        wxApi.setStartPage();
        this.setData({
          logged: res,
        });
      });
    }
  },
  golink(e) {
    const data = e.currentTarget.dataset || e.target.dataset;
    //转为小写并去除左右空格
    var str = data.url.toLowerCase();
    if (str != "") {
      if (str.indexOf('https') === 0 || str.indexOf('http') === 0) {
        wxApi.navigateTo("/pages/web/web?id=" + str);
      } else if (str.indexOf('mm://') == 0) {
        var array = str.split('_');
        if (array[0].replace("mm://", "") == 'shop') {
          wxApi.navigateTo('/pages/companydetail/index', {
            id: array[1]
          });
        }
      } else if (str.indexOf('ym://') == 0) {
        var url = str.replace("ym://", "");
        if(url.indexOf('subpackages')>0){
          url = url.replace("subpackages", "subPackages");
        }
        wxApi.navigateTo(url);
      } else {
        wxApi.navigateTo("/pages/goods/goods?id=" + str);
      }
    }

  },
  /**
   * 获取用户信息
   */
  getUserInfo(cb) {
    //显示导航条加载
    wx.showNavigationBarLoading();
    //第一部分数据
    http.post(api.default, {
      data: {
        action: 'getuserinfo',
        userid: this.data.userId,
      }
    }, false).then(res => {
      const userInfo = res.data.data;
      console.log(userInfo);
      this.setData({
        user_model:userInfo.user_model
      })
      if (userInfo.user_model.user_rank == 1) {
        this.setData({
          rankname: "普通会员"
        });
      } else if (userInfo.user_model.user_rank == 2) {
        this.setData({
          rankname: "建材门店"
        });
      } else if (userInfo.user_model.user_rank == 3) {
        this.setData({
          rankname: "装修公司"
        });
      } else if (userInfo.user_model.user_rank == 4) {
        this.setData({
          rankname: "设计师"
        });
      }
      //第二部分数据
      http.post(api.default, {
        data: {
          action: 'userdefault',
          userid: this.data.userId,
        }
      }, true).then(res => {
        console.log(11111111111111,res.data.data)
        const userData = res.data.data;
        console.log('--------------------------pay_points',userData.pay_points)
        var nickname = "";
        this.setData({
          userInfo: userInfo,
          userData: userData,
          vipname: userData.vipname,
          endtime: userData.endtime,
          parentid: userData.shop?.parentid,
          user_money: userData.user_money,
          bank: userData.bank,
          pay_points: userData.pay_points,
          botZtList: userData.botZtList,
          v_count: userData.v_count
        });
        app.globalData.v_count = this.data.v_count;
        this.getTabBar().setData({
          v_count: app.globalData.v_count
        });
        if(userData.v_count>0){
          // this.setData({
          //   newFKPop:true
          // })
        }
        if (userData.shop != null && userData.shop.ShopName != null) {
          nickname = userData.shop.ShopName;
        } else {
          nickname = userInfo.user_model.nickname;
        }
        this.setData({
          nickname: nickname
        });
        console.log(userInfo);
        cb && cb();
        wx.hideLoading();
        //关闭导航条加载
        wx.hideNavigationBarLoading();
      });
    });
  },

  imageAvatar(str) {
    if (str != null && typeof (str) !== 'undefined' && str != "") {
      if (str.indexOf('http') === 0 || str.indexOf('https') === 0) {
        return str
      } else if (str.toLowerCase().indexOf('users') === 0) {
        return 'https://keju123.oss-cn-shanghai.aliyuncs.com/' + str + this.thumbSize(100);
      } else {
        return str;
      }
    } else {
      return ''
    }
  },

  goBalance() {
    let { user_model } = this.data;
    if(!user_model.head_url || !user_model.nickname){
      $toast('请先完善信息')
      this.setData({
        iswxbind:true
      })
    }else{
      SubscribeMessage().then(()=>{
        wxApi.navigateTo(getPage.userbalance);
      })
    }
  },
  goshopcoupon(e) {
    wxApi.navigateTo(getPage.couponshop, {
      id: e.currentTarget.dataset.id
    });
  },

  thumbSize(str) {
    if (typeof (str) !== 'undefined') {
      return '?x-oss-process=image/resize,m_fill,h_' + str + ',w_' + str
    }
  },


  mesclick() {
    // wx.requestSubscribeMessage({
    //   tmplIds: ['3yWycWSutPwvqyqntpigXDBpfgcdgAQyKXoOp_l_0d4'],
    //   success(res) {
    //     console.log(res);
    //   }
    // })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    // //判断是否登录
    // app.getLogin().then((res) => {
    //   //console.log(res);
    //   this.setData({
    //     localInfo: res,
    //     logged: res.code,
    //     userId: res.data.user.user_id,
    //     userRank: res.data.user.user_rank,
    //   });
    //   //获取页面数据
    //   this.getUserInfo(() => {
    //     let {
    //       localInfo,
    //       userInfo
    //     } = this.data;
    //     //更新本地
    //     localInfo.data.user = userInfo.user_model;
    //     this.setData({
    //       localInfo
    //     });
    //     storage.set('userInfo', localInfo);
    //     // if (userInfo.user_model.user_rank == 2) {
    //     //   wx.setNavigationBarColor({
    //     //     frontColor: '#ffffff', // 必写项
    //     //     backgroundColor: '#e30020', // 必写项
    //     //   }); 
    //     // }
    //   });
    // }).catch((res) => {
    //   this.setData({
    //     logged: res,
    //   });
    //   this.goLogin();
    // }).finally(() => {
    //   this.nv
    //   this.setData({
    //     initial: 1
    //   });


    // });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  // 获取未读消息数
  getunreadmsg() {
    http.post(api.default, {
      data: {
        action: 'getmsgcount',
        userid: this.data.userId
      }
    }, false).then(res => {
      let {
        data
      } = res.data;
      let unReadMsg = data.msgcount + data.fw_notice + data.sys_notice
      app.globalData.unReadMsg = unReadMsg;
      if (typeof this.getTabBar === "function" && this.getTabBar()) {
        console.log('get===', this.getTabBar())
        this.getTabBar().setData({
          number: app.globalData.unReadMsg,
        });
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      beforeClose: (action) => this.onBeforeClose(action)
    })

    //判断是否登录
    app.getLogin().then((res) => {
      console.log('user_show------------', res);
      this.setData({
        localInfo: res,
        logged: res.code,
        userId: res.data.user.user_id,
        shopid: res.data.shop ? res.data.shop.ShopId : 0,
        userRank: res.data.user.user_rank,
        bindwx: res.data.bindwx ? true : false, //返回1需要绑定微信弹窗 0不需要
      });

      if (typeof this.getTabBar === "function" && this.getTabBar()) {
        this.getTabBar().setData({
          // 这里的数字对应tabbar对应的索引
          selected: 4,
          v_count: app.globalData.v_count,
        });
        console.log('this.getTabBar()', this.getTabBar())
        let getTabBar = this.getTabBar();
        this.getunreadmsg();
        this.setData({
          myTime: setInterval(function () {
            // console.log('getTabBar',getTabBar)
            getTabBar.setData({
              number: app.globalData.unReadMsg
            });
          }, 5000)
        })
      }
      
      //获取页面数据
      this.getUserInfo(() => {
        let {
          localInfo,
          userInfo,
          userData
        } = this.data;
        //更新本地
        localInfo.data.user = userInfo.user_model;
        localInfo.data.shop = userData.shop;
        this.setData({
          localInfo
        });
        console.log('localInfo===========', localInfo)
        storage.set('userInfo', localInfo);
        // if (userInfo.user_model.user_rank == 2) {
        //   wx.setNavigationBarColor({
        //     frontColor: '#ffffff', // 必写项
        //     backgroundColor: '#e30020', // 必写项
        //   }); 
        // }
        
        // 角标
        console.log('this.data.userData.shop====',this.data.userData)
        console.log('this.data.userid====',this.data.userId)
        console.log('this.data.shopid====',this.data.shopid)
        if(userData.shop==null){
          let key = 'nullShopJbData' + this.data.userId
          let nullShopJbData = wx.getStorageSync(key)
          console.log('nullShopJbData===',nullShopJbData)
          this.setData({
            key
          })
          if(nullShopJbData){
            this.setData({
              nullShopJbData
            })
          }else{
            let firstData = {
              collection: 1,
              zuji: 1,
              beforeShenqing: 1,
              userProfile: 1,
              useryhk: 1,
              orderuser: 1,
              password: 1,
              myxuqiu: 1,
              couponList: 1,
              choujiang: 1,
              address: 1,
              yuangong: 1,
              kefu:1,
            }
            this.setData({
              nullShopJbData:firstData
            })
            wx.setStorageSync(key,firstData)
          }
        }else{
          let key = 'shopJbData' + this.data.shopid
          this.setData({
            key
          })
          let shopJbData = wx.getStorageSync(key)
          console.log('shopJbData===',shopJbData)
          if(shopJbData){
            this.setData({
              shopJbData
            })
          }else{
            let firstData = {
              userProfile: 1,
              useryhk: 1,
              collection: 1,
              zuji: 1,
              password: 1,
              couponList: 1,
              yuangong: 1,
              orderuser: 1,
              yongjinShop: 1,
              mycase: 1,
              shopedit: 1,
              admin: 1,
              companydetail:1,
              myproductsCate:1,
              pingjia:1,
              sekalist:1,
              desworks:1,
              shopDw:1,
              ordermanage:1,
              dataCenter:1,
              shareMy:1,
              shareUser:1,
              jingzhunUser:1,
              putin:1,
              cityPutin:1,
              activitybm:1,
              platform:1,
              kefu:1
            }
            this.setData({
              shopJbData:firstData
            })
            wx.setStorageSync(key,firstData)
          }
        }
      });

      
    }).catch((res) => {
      this.setData({
        logged: res,
      });
      // console.log("catch===================", res);
      this.goLogin();
    }).finally(() => {
      this.nv
      this.setData({
        initial: 1
      });
    });
  },

  newFKPopupClose(){
    this.setData({
      newFKPop:false
    })
  },
  gotoJingzhun(){
    this.setData({
      newFKPop:false
    })
    wxApi.navigateTo(getPage.jingzhunUser);
  },

  gouserpoints(){
    wxApi.navigateTo(getPage.userpoints);
  },

  onChooseAvatar(e) {
    const {
      avatarUrl
    } = e.detail
    let that = this;
    uploadImage({
      filePath: avatarUrl,
      dir: "users",
      success(res) {
        that.setData({
          "wxinfo.avatar": res
        })
      },
      fail(res) {
        $toast(`头像上传失败${res}`);
      }
    });
  },

  wxinputname(e) {
    this.setData({
      "wxinfo.nickname": e.detail.value
    })
  },

  onBeforeClose: function (action) {
    let {
      wxinfo,
      userInfo
    } = this.data;
    return new Promise((resolve) => {
      if (action === 'confirm') { // 点击确认
        if (!wxinfo.avatar || !wxinfo.nickname) {
          wx.showToast({
            title: '请选择头像和昵称',
            icon: 'none'
          })
          resolve(false) // 阻止弹框关闭
        } else { // 校验通过
          this.wxAvatarConfirm() // 提交数据，并设置变量是否允许弹框关闭
          resolve(this.data.dialogConfirm)
        }
      } else { // 点击取消
        resolve(true)
        this.setData({
          iswxbind: false
        })
      }
    })
  },

  wxAvatarConfirm() {
    let {
      wxinfo
    } = this.data;
    // userid   用户ID 、head_img  头像、nickname  昵称
    let params = {
      action: 'updateuserinfo',
      userid: this.data.userId,
      head_img: wxinfo.avatar,
      nickname: wxinfo.nickname
    };

    http.post(api.default, {
      data: params
    }, false).then(res => {
      this.setData({
        iswxbind: false
      })
      this.setData({
        dialogConfirm: true
      })
      let {
        localInfo
      } = this.data;
      // 更新本地存储数据
      localInfo.data.user.head_url = res.data.data.head_url;
      localInfo.data.user.nickname = res.data.data.nickname;
      localInfo.data.bindwx = 0;
      storage.set('userInfo', localInfo);
      this.getUserInfo(() => {
        let {
          localInfo,
          userInfo,
          userData
        } = this.data;
        //更新本地
        localInfo.data.user = userInfo.user_model;
        localInfo.data.shop = userData.shop;
        this.setData({
          localInfo
        });
        storage.set('userInfo', localInfo);
      });
    }).catch(() => {
      this.setData({
        dialogConfirm: false
      })
    })
  },

  wxAvatarClose() {
    this.setData({
      iswxbind: false
    })
  },

  upload_file: function (tempFilePathImg) {
    var that = this;
    wx.uploadFile({
      filePath: tempFilePathImg,
      name: 'file',
      url: getApp().globalData.url + 'common/upload',
      formData: {
        'data': 'bank_img'
      },
      success: (res) => {
        console.log('ssssssssss', res)
        wx.hideLoading();
        const bank_img = JSON.parse(res.data).img; //把数据字符串转变成对象
        if (bank_img) {
          that.setData({
            bank_img: bank_img,
            isShow: true
          })
        }
        that.triggerEvent('chooseMedia', bank_img)
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    console.log('user_onHide________清除定时器~')
    clearInterval(this.data.myTime);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    if (this.data.logged) {
      //抖动
      wx.vibrateShort();
      this.getUserInfo(() => {
        let {
          localInfo,
          userInfo,
          userData
        } = this.data;
        console.log(this.data);
        //更新本地
        localInfo.data.user = userInfo.user_model;
        localInfo.data.shop = userData.shop;
        this.setData({
          localInfo
        });
        storage.set('userInfo', localInfo);
        wx.stopPullDownRefresh();
      });
    } else {
      wx.stopPullDownRefresh();
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },
})